package com.ncc.interview.myQueue;

/**
 * @author pengxiong
 * @date 2022/3/29
 * @Description 实现队列 push, pop, peek, empty
 * @since
 */
public class NccQueue<T> {

	private final int queueSize;
	private final T[] values;
	private int head;
	private int tail;

	private int cnt;

	public NccQueue(int size){
		this.queueSize = size;
		values = (T[]) new Object[size];
		head = 0;
		tail = 0;
		cnt = 0;
	}

	public void push(T value){
		if (queueSize == cnt){
			throw new RuntimeException("队列已满，不能添加");
		}
		values[tail] = value;
		tail++;
		// 遇到尾部则往前走
		tail %= queueSize;
		cnt++;
	}

	public T pop(){
		if (empty()){
			throw new RuntimeException("队列为空，不能出列");
		}
		T value = values[head];
		values[head] = null;
		head++;
		head %= queueSize;
		// 队列数量减一
		cnt--;
		return value;
	}
	public T peek(){
		if (empty()){
			throw new RuntimeException("队列为空，不能出列");
		}
		return values[head];
	}

	public boolean empty(){
		return cnt == 0;
	}

	public int size() {
		return cnt;
	}
}
